package com.kelvin.paopao.widgets;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kelvin.kelvinlib.bitmap.BitmapUtil;
import com.kelvin.kelvinlib.utils.CommonUtil;
import com.kelvin.kelvinlib.utils.ToastUtil;
import com.kelvin.paopao.R;
import com.kelvin.paopao.adapter.PersonPhotoImageAdapter;
import com.kelvin.paopao.api.RetrofitService;
import com.kelvin.paopao.api.responseBean.CommonListResponse;
import com.kelvin.paopao.api.responseBean.PersonPhotoModel;
import com.kelvin.paopao.module.person.photoset.PhotoSetActivity;
import com.kelvin.paopao.utils.DialogMaker;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2017/5/14.
 */

public class PersonPhotoEditView extends RecyclerView {

    private PersonPhotoImageAdapter adapter;
    private View headView;
    private LinearLayoutManager manager;


    private List<PersonPhotoModel> newWorkPhotos;

    public PersonPhotoEditView(Context context) {
        super(context);
        init(context, null);
    }

    private void init(Context context, AttributeSet attrs) {

    }

    public PersonPhotoEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public void create(Context context) {
        adapter = new PersonPhotoImageAdapter(context);
        headView = LayoutInflater.from(context).inflate
                (R.layout.img_head_add_view, (ViewGroup) getParent(), false);

        headView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listner != null) {
                    listner.addImage();
                }
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_delete) {
                    showDeleteDialog(position);
                } else if (view.getId() == R.id.iv) {
                    List<String> urls = new ArrayList<String>();
                    urls.add((String) adapter.getData().get(position));
                    PhotoSetActivity.launch(getContext(), urls, 0);
                }
            }
        });
        manager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true);
        setLayoutManager(manager);
        setAdapter(adapter);
        adapter.addHeaderView(headView);
        adapter.setNewData(null);
    }

    /**
     * 移除当前位置的图
     *
     * @param position
     */
    private void removePositionImage(final int position) {
        if (CommonUtil.isUrlImage(adapter.getData().get(position))) {
            RetrofitService.removePersonPhoto(String.valueOf(findNetworkId(adapter.getData().get(position))))
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<CommonListResponse>() {
                @Override
                public void accept(@NonNull CommonListResponse commonListResponse) throws Exception {
                    if (commonListResponse.getReason().equals("成功")) {
                        adapter.remove(position);
                    }
                }
            });
        } else {
            adapter.remove(position);
        }
    }

    public void addImageView(final String imgPath) {
        //使用鲁班压缩图片
        Luban.get(getContext())
                .load(new File(imgPath))                     //传人要压缩的图片
                .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        DialogMaker.showProgressDialog(getContext(), "图片压缩中~~");
                    }

                    @Override
                    public void onSuccess(final File file) {
                        Observable.create(new ObservableOnSubscribe<File>() {
                            @Override
                            public void subscribe(@NonNull ObservableEmitter<File> e) throws Exception {
                                e.onNext(file);
                            }
                        }).flatMap(new Function<File, ObservableSource<CommonListResponse>>() {
                            @Override
                            public ObservableSource<CommonListResponse> apply(@NonNull File file) throws Exception {
                                String base64 = BitmapUtil.fileToBase64(file);
                                base64.replace("+", "%2B");
                                return RetrofitService.addPersonPhoto(base64);
                            }
                        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                                subscribe(new Consumer<CommonListResponse>() {
                                    @Override
                                    public void accept(@NonNull CommonListResponse commonListResponse) throws Exception {
                                        adapter.addData(imgPath);
                                        DialogMaker.diamiss();
                                    }
                                }, new Consumer<Throwable>() {
                                    @Override
                                    public void accept(@NonNull Throwable throwable) throws Exception {
                                        ToastUtil.showToast(getContext(), "添加相册失败");
                                        DialogMaker.diamiss();
                                    }
                                }, new Action() {
                                    @Override
                                    public void run() throws Exception {
                                        DialogMaker.diamiss();
                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogMaker.diamiss();
                    }
                }).launch();
    }

    public interface AddImgListner {
        void addImage();
    }

    private AddImgListner listner;

    public void setListener(AddImgListner listener) {
        this.listner = listener;
    }

    public void setNetWorkImage(List<PersonPhotoModel> netWorkPhoto) {
        this.newWorkPhotos = netWorkPhoto;
        for (PersonPhotoModel model : netWorkPhoto) {
            adapter.addData(model.getUserimg());
        }
    }

    /**
     * 查找出网络图片的id
     */
    private int findNetworkId(String httpPath) {
        for (PersonPhotoModel model : newWorkPhotos) {
            if (model.getUserimg().equals(httpPath)) {
                return model.getId();
            }
        }
        return 0;
    }

    private void showDeleteDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示").setMessage("是否确定删除该图片").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                removePositionImage(position);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }
}
